#include "control_light_alarm.h"
#include "ui_control_light_alarm.h"
#include<QDebug>
#include"signsls_slots.h"

Control_light_alarm::Control_light_alarm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Control_light_alarm),
    m_hub(&SignslS_SlotS::getInstance())
{
    ui->setupUi(this);
    file.setFileName("/sys/devices/platform/leds/leds/sys-led/brightness");
    file2.setFileName("/sys/devices/platform/leds/leds/beep/brightness");

    if (!file.exists()){
        ui->light_btn->setText("未获取到 LED 设备！");
    }
    getLedState();
    if (!file.exists())
    /* 设置按钮的初始化文本 */
    ui->alarm_btn->setText("未获取到 BEEP 设备！");

    /* 获取 BEEP 的状态 */
    getBeepState();
    connect(m_hub, &SignslS_SlotS::openlight, this,&Control_light_alarm::openlight);
}
void Control_light_alarm::setBeepState()
{
    bool state = getBeepState();

    /* 如果文件不存在，则返回 */
    if (!file.exists())
    return;

    if(!file.open(QIODevice::ReadWrite))
    qDebug()<<file.errorString();

    QByteArray buf[2] = {"0", "1"};

    if (state)
        file.write(buf[0]);
    else
        file.write(buf[1]);

    file.close();

    getBeepState();
}

bool Control_light_alarm::getBeepState()
{
    /* 如果文件不存在，则返回 */
    if (!file.exists())
        return false;

    if(!file.open(QIODevice::ReadWrite))
        qDebug()<<file.errorString();

    QTextStream in(&file);

    /* 读取文件所有数据 */
    QString buf = in.readLine();

    /* 打印出读出的值 */
    qDebug()<<"buf: "<<buf<<endl;
    file.close();
    if (buf == "1") {
        ui->alarm_btn->setText("BEEP 开");
            return true;
        } else {
        ui->alarm_btn->setText("BEEP 关");
        return false;
        }
}


void Control_light_alarm::setLedState()
{
    bool state = getLedState();
    if (!file.exists())
        return;
    if(!file.open(QIODevice::ReadWrite))
        qDebug()<<file.errorString();
    QByteArray buf[2] = {"0", "1"};
    if (state)
        file.write(buf[0]);

    else
         file.write(buf[1]);

    /* 关闭文件 */
    file.close();

    /*重新获取 LED 的状态 */
    getLedState();
}

bool Control_light_alarm::getLedState()
{
    if (!file.exists())
        return false;
    if(!file.open(QIODevice::ReadWrite))
        qDebug()<<file.errorString();
    QTextStream in(&file);
    QString buf = in.readLine();
    qDebug()<<"buf: "<<buf<<endl;
    file.close();
    if (buf == "1") {
        ui->light_btn->setText("LED 点亮");
        return true;
    } else {
        ui->light_btn->setText("LED 熄灭");
        return false;
    }
}

Control_light_alarm::~Control_light_alarm()
{
    delete ui;
}

void Control_light_alarm::on_light_btn_clicked()
{
    setLedState();
}

void Control_light_alarm::on_pushButton_clicked()
{
    emit show_Menu();
}

void Control_light_alarm::on_alarm_btn_clicked()
{
    setBeepState();
}

void Control_light_alarm::openlight()
{
    qDebug()<<434343;
     setLedState();
}
